package org.an.proj.contacts.ui.contact;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import com.bigkoo.pickerview.TimePickerView;
import de.hdodenhof.circleimageview.CircleImageView;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.an.ku.util.SimpleTextWatcher;
import org.an.ku.util.StringUtil;
import org.an.ku.util.ToastUtil;
import org.an.ku.view.MyTextView;
import org.an.ku.view.dialog.chose.ChooseDialog;
import org.an.ku.view.dialog.chose.ChooseDialogInfo;
import org.an.ku.view.fulllist.FullListView;
import org.an.ku.view.indexview.PinYinUtil;
import org.an.proj.contacts.R;
import org.an.proj.contacts.adapter.PhoneAdapter;
import org.an.proj.contacts.adapter.QqAdapter;
import org.an.proj.contacts.db.DBManager;
import org.an.proj.contacts.db.dao.ContactInfoDao;
import org.an.proj.contacts.db.dao.GroupInfoDao;
import org.an.proj.contacts.db.dao.PhoneInfoDao;
import org.an.proj.contacts.eventbus.EventController;
import org.an.proj.contacts.eventbus.EventTag;
import org.an.proj.contacts.model.ContactInfo;
import org.an.proj.contacts.model.GroupInfo;
import org.an.proj.contacts.model.PhoneInfo;
import org.an.proj.contacts.ui.base.BaseActivity;
import org.an.proj.contacts.ui.contact.view.ContactItemBlockView;
import org.an.proj.contacts.ui.contact.view.MoreAttrsDialog;
import org.greenrobot.eventbus.EventBus;

/**
 * Created by Fcy on 2016/10/16.<br/>
 * 编辑/查看联系人界面
 */
public class ContactDetailActivity extends BaseActivity
  implements ContactItemBlockView.IOnDeleteListener, MoreAttrsDialog.OnItemClickListener,
  View.OnClickListener, TimePickerView.OnTimeSelectListener,
  ChooseDialog.OnSingleItemClickListener {
  @Bind(R.id.title_bar) RelativeLayout mTitleBar;
  @Bind(R.id.iv_avatar) CircleImageView mIvAvator;
  @Bind(R.id.edt_name) EditText mEdtName;
  @Bind(R.id.ll_phone_bar) LinearLayout mLlPhoneBar;
  @Bind(R.id.ll_qq_bar) LinearLayout mLlQqBar;
  @Bind(R.id.ll_other_bar) LinearLayout mLlOtherBar;
  @Bind(R.id.tv_picker_group) MyTextView mTvPickerGroup;
  @Bind(R.id.flv_phone) FullListView mFlvPhone;
  @Bind(R.id.flv_qq) FullListView mFlvQq;
  @Bind(R.id.item_profession) ContactItemBlockView mItemProfession;
  @Bind(R.id.item_address) ContactItemBlockView mItemAddress;
  @Bind(R.id.item_birthday) ContactItemBlockView mItemBirthday;
  @Bind(R.id.item_note) ContactItemBlockView mItemNote;

  private List<PhoneInfo> mPhoneInfoList = new ArrayList<>();
  private List<String> mQqList = new ArrayList<>();
  private ContactInfo mContactInfo;

  private PhoneAdapter mPhoneAdapter;
  private QqAdapter mQqAdapter;
  private MoreAttrsDialog mMoreAttrDialog;
  private String[] mMoreAttrs;
  private final List<ChooseDialogInfo> mMoreAttrsInfos = new ArrayList<>();
  private TimePickerView mTimePicker;
  private static SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  private ChooseDialog mGroupChooseDialog;

  private ContactInfoDao mContactDao;
  private PhoneInfoDao mPhoneDao;
  private GroupInfoDao mGroupInfoDao;

  @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_addcontact);
    //setStatusBarColor(Color.BLUE);
    ButterKnife.bind(this);
    init();
  }

  //@Override public boolean dispatchTouchEvent(MotionEvent ev) {
  //  SoftInputUtil.dispatchTouchEvent(this, ev);
  //  return super.dispatchTouchEvent(ev);
  //}

  private void init() {
    mContactDao = DBManager.getDaoSession().getContactInfoDao();
    mPhoneDao = DBManager.getDaoSession().getPhoneInfoDao();
    initGroupData();

    setTitle(R.string.str_add_contact);
    mContactInfo = new ContactInfo();
    mContactInfo.qqInfos = mQqList;

    mPhoneAdapter = new PhoneAdapter(this);
    mFlvPhone.setAdapter(mPhoneAdapter);
    mPhoneInfoList.add(new PhoneInfo().getDefaultPhone());
    mPhoneAdapter.setData(mPhoneInfoList);

    mQqAdapter = new QqAdapter(this);
    mFlvQq.setAdapter(mQqAdapter);
    mQqList.add("");
    mQqAdapter.setData(mQqList);

    mMoreAttrDialog = new MoreAttrsDialog(this, getString(R.string.str_add_moreattr));
    mMoreAttrDialog.setMaxItemCount(4).setItemTextColorId(R.color.color_item_more_attr);
    mMoreAttrDialog.setOnItemClickListener(this);
    mMoreAttrs = mContext.getResources().getStringArray(R.array.more_attrs);

    int[] moreAttrsParams = mContext.getResources().getIntArray(R.array.more_attrs＿code);
    // 如果是详情模式，要根据数据构建出ChooseDialogInfo
    for (int i = 0; i < mMoreAttrs.length; i++) {
      mMoreAttrsInfos.add(new ChooseDialogInfo(null, false, mMoreAttrs[i], moreAttrsParams[i]));
    }
    mMoreAttrDialog.setData(mMoreAttrsInfos);

    mItemProfession.setData(mMoreAttrs[2], getString(R.string.str_input_profession));
    mItemAddress.setData(mMoreAttrs[3], getString(R.string.str_input_address));
    mItemBirthday.setEditable(false).setData(mMoreAttrs[4], getString(R.string.str_input_birthday));
    mItemBirthday.mEdtInput.setOnClickListener(this);
    mItemNote.setData(mMoreAttrs[5], getString(R.string.str_input_note));
    mItemProfession.addTextChangedListener(new SimpleTextWatcher() {
      @Override public void afterTextChanged(String s) {
        mContactInfo.setProfession(s);
      }
    });
    mItemAddress.addTextChangedListener(new SimpleTextWatcher() {
      @Override public void afterTextChanged(String s) {
        mContactInfo.setAddress(s);
      }
    });
    mItemNote.addTextChangedListener(new SimpleTextWatcher() {
      @Override public void afterTextChanged(String s) {
        mContactInfo.setNote(s);
      }
    });
    mEdtName.addTextChangedListener(new SimpleTextWatcher() {
      @Override public void afterTextChanged(String s) {
        mContactInfo.setName(s);
      }
    });

    mItemProfession.setOnDeleteListener(this);
    mItemAddress.setOnDeleteListener(this);
    mItemBirthday.setOnDeleteListener(this);
    mItemNote.setOnDeleteListener(this);
  }

  /**
   * 初始化分组
   */
  private void initGroupData() {
    mGroupChooseDialog = new ChooseDialog(mContext);
    mGroupChooseDialog.bindTextView(mTvPickerGroup)
      .setTitle("请选择分组")
      .setMaxItemCount(4)
      .setOnSingleItemClickListener(this);

    // 从数据库中读取
    mGroupInfoDao = DBManager.getDaoSession().getGroupInfoDao();
    List<GroupInfo> groupInfos = mGroupInfoDao.loadAll();
    List<ChooseDialogInfo> mGroupChooseList = new ArrayList<>();
    for (GroupInfo groupInfo : groupInfos) {
      mGroupChooseList.add(
        new ChooseDialogInfo(null, false, groupInfo.getGroupName(), groupInfo.getId()));
    }
    mGroupChooseDialog.setData(mGroupChooseList);
  }

  /**
   * @action 保存
   */
  @OnClick(R.id.btn_save) public void onSave() {
    if (!checkName()) return;
    mContactInfo.transToDB();
    // 事务操作
    DBManager.getDaoSession().runInTx(new Runnable() {
      @Override public void run() {
        long contactId = mContactDao.insert(mContactInfo);
        //  保存电话，需要设置联系人id
        for (int i = 0; i < mPhoneInfoList.size(); i++) {
          PhoneInfo phoneInfo = mPhoneInfoList.get(i);
          if (phoneInfo.isInvalid()) continue;
          phoneInfo.setContactId(contactId);
          mPhoneDao.insert(phoneInfo);
        }
        finish();
        EventController.postRefreshContactsEvent();
      }
    });
  }

  /**
   * 检验姓名，有效则保存数据库
   *
   * @return 是否有效
   */
  private boolean checkName() {
    String name = StringUtil.trim(mContactInfo.getName());
    if (TextUtils.isEmpty(name)) {
      ToastUtil.toast(this, "姓名不能为空");
      return false;
    }
    // 校验是否存在改姓名，如果不存在则赋值pinyin和jianpin
    if (hasName(name)) {
      ToastUtil.toast(this, String.format("联系人'%s'已经存在", mContactInfo.getName()));
      return false;
    }

    mContactInfo.setPinyin(PinYinUtil.toPinyin(name));
    mContactInfo.setJianpin(PinYinUtil.toJianPin(name));
    mContactInfo.setIndex(getIndex(mContactInfo.getJianpin()));
    return true;
  }

  private String getIndex(String jianpin) {
    if (!TextUtils.isEmpty(jianpin)) {
      char c = jianpin.charAt(0);
      if (c >= 'A' && c <= 'Z') {
        // 统一转成大写，实际上存简拼的时候已经是大写了
        return String.valueOf(c).toUpperCase();
      }
    }
    // 由于ASCII码，'#'在字母前面，排序要写个后面的
    return "~";
  }

  /**
   * 是否包含这个name
   *
   * @param name name
   */
  private boolean hasName(String name) {
    // 查询name列
    //ContactInfo contactInfo = mContactDao.loadByRowId(ContactInfoDao.Properties.Name.ordinal);
    //Log.i("fcy", "loadByRowId 1=" + (contactInfo == null ? "null" : contactInfo.toString()));
    // 查询name和指定name相同的个数
    long count = mContactDao.queryBuilder().where(ContactInfoDao.Properties.Name.eq(name)).count();
    return count > 0;
  }

  @OnClick({ R.id.btn_more, R.id.tv_picker_group }) public void bindClick(View view) {
    switch (view.getId()) {
      case R.id.btn_more:
        EventBus.getDefault().post(new EventTag.TagChatMsgRefresh());
        mMoreAttrDialog.show();
        break;
      case R.id.tv_picker_group:
        if (mGroupChooseDialog.getDatas().size() == 0) {
          ToastUtil.toast(mContext, R.string.toast_no_group);
        } else {
          mGroupChooseDialog.show();
        }
        break;
    }
  }

  /**
   * 删除
   */
  @Override public void onDelete(ContactItemBlockView parent, View btnDel) {
    if (parent == mItemProfession) {
      showSingleItem(parent, false, mMoreAttrsInfos.get(2));
    } else if (parent == mItemAddress) {
      showSingleItem(parent, false, mMoreAttrsInfos.get(3));
    } else if (parent == mItemBirthday) {
      showSingleItem(parent, false, mMoreAttrsInfos.get(4));
    } else if (parent == mItemNote) {
      showSingleItem(parent, false, mMoreAttrsInfos.get(5));
    }
  }

  /**
   * 添加更多属性
   *
   * @param position 列表下标
   * @param info 点击position处的info
   */
  @Override public void onItemClick(int position, ChooseDialogInfo info) {
    int value = (int) info.value;
    switch (value) {
      case 100: // 电话
        mPhoneInfoList.add(new PhoneInfo().getDefaultPhone());
        mPhoneAdapter.notifyDataSetChanged();
        mMoreAttrDialog.dismiss();
        break;
      case 110: // ＱＱ
        mQqList.add("");
        mQqAdapter.notifyDataSetChanged();
        mMoreAttrDialog.dismiss();
        break;
      case 120: // 职业
        clickMoreAttrs(mItemProfession, info);
        break;
      case 130: // 住址
        clickMoreAttrs(mItemAddress, info);
        break;
      case 140: // 生日
        clickMoreAttrs(mItemBirthday, info);
        break;
      case 150: // 备注
        clickMoreAttrs(mItemNote, info);
        break;
    }
  }

  /**
   * 点击添加更多
   */
  private void clickMoreAttrs(ContactItemBlockView view, ChooseDialogInfo info) {

    /*if (info.isSelect) {
      ToastUtil.toast(this, info.text + "已添加");
    } else {
      mMoreAttrDialog.dismiss();
      showSingleItem(view, true, info);
    }*/
  }

  /**
   * @param view view
   * @param isShow 是否显示
   * @param info 改view对应的dialogInfo
   */
  private void showSingleItem(ContactItemBlockView view, boolean isShow, ChooseDialogInfo info) {
    info.setSelect(isShow);
    if (!isShow) view.clearEdit();
    view.setVisibility(isShow ? View.VISIBLE : View.GONE);
  }

  private DatePicker mDatePicker;

  @Override public void onClick(View v) {
    if (v == mItemBirthday.mEdtInput) {
      //if (mTimePicker == null) {
      //mTimePicker = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
      //mTimePicker.setTitle("请选择生日");
      //mTimePicker.setTime(new Date());
      //mTimePicker.setCyclic(false);
      //mTimePicker.setOnTimeSelectListener(this);
      //}
      //mTimePicker.show();

      mDatePicker = new DatePicker(this, DatePicker.YEAR_MONTH_DAY);
      mDatePicker.setRangeStart(1900, 1, 1);//开始范围
      mDatePicker.setRangeEnd(2100, 1, 1);//结束范围
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(new Date());
      // setSelectedItem这个方法不好用，应该添加一个参数为Data或者时间戳的
      mDatePicker.setSelectedItem(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
        calendar.get(Calendar.DAY_OF_MONTH));
      mDatePicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
        @Override public void onDatePicked(String year, String month, String day) {
          mDatePicker.dismiss();
          // 这个回调不好，应该多一个参数Data，有的只是为了要时间戳
          Calendar calendar = Calendar.getInstance();
          calendar.set(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day));
          mContactInfo.setBirthday(calendar.getTimeInMillis());
          mItemBirthday.mEdtInput.setText(sDateFormat.format(calendar.getTime()));
        }
      });
      mDatePicker.show();
    }
  }

  @Override public void onTimeSelect(Date date, Object o) {
    mTimePicker.dismiss();
    mContactInfo.setBirthday(date.getTime());
    mItemBirthday.mEdtInput.setText(sDateFormat.format(date));
  }

  /**
   * 选择分组
   *
   * @param position 列表下标
   */
  @Override public void onSingleItemClick(ChooseDialog dialog, int position,
    ChooseDialogInfo info) {
    mContactInfo.setGroupId((Long) info.value);
  }
}
